package com.guoliang.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.guoliang.eduService.entity.EduSubject;
import com.guoliang.eduService.entity.excel.ExcelObjectData;
import com.guoliang.eduService.service.EduSubjectService;
import com.guoliang.service.exceptionHandler.MyException;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author ：Leo
 * @date ：Created in 2023/1/17 18:44
 * @description：
 */
public class SubjectExcelListener extends AnalysisEventListener<ExcelObjectData> {
    private EduSubjectService eduSubjectService;

    public SubjectExcelListener() {
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void invoke(ExcelObjectData excelObjectData, AnalysisContext analysisContext) {
       if (excelObjectData==null) {
           throw new MyException(20001, "文件数据为空");
       }
       String title=excelObjectData.getOneSubjectName();
       EduSubject eduSubject=existOneEduSubject(title);
       if (eduSubject==null){
           //不存在一级目录 先保存一级目录
           eduSubject=new EduSubject();
           eduSubject.setParentId("0");
           eduSubject.setTitle(title);
           eduSubjectService.save(eduSubject);
       }
       //添加二级分类
        String pid=eduSubject.getId();
       String title2= excelObjectData.getTwoSubjectName();
        EduSubject eduSubject2=existTwoEduSubject(title2,pid);
        if (eduSubject2==null){
            eduSubject2=new EduSubject();
            eduSubject2.setTitle(title2);
            eduSubject2.setParentId(pid);
            eduSubjectService.save(eduSubject2);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
    private EduSubject existOneEduSubject(String name){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",0);
        return eduSubjectService.getOne(wrapper);
    }
    private EduSubject existTwoEduSubject(String name,String pid){
        QueryWrapper<EduSubject> wrapper=new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        return eduSubjectService.getOne(wrapper);
    }
}
